package app.common.utils;

import com.gitee.feizns.dynamic.function.ThrowableRunnable;
import lombok.RequiredArgsConstructor;

/**
 * 重试
 * @author feizns
 * @since 2023/07/20
 */
public abstract class Retry {

    /**
     * 设置
     * @param retryCount 重试计数
     * @return {@link RetrySetting}
     */
    public static RetrySetting setting(int retryCount) {
        return new RetrySetting(retryCount);
    }

    /**
     * 重试设置
     * @author feizns
     * @since 2023/07/20
     */
    @RequiredArgsConstructor
    public static class RetrySetting {

        /**
         * 重试
         */
        private final int count;

        /**
         * 重试执行指定次数的代码执行
         * @param runnable 可运行
         */
        public void execute(ThrowableRunnable runnable) {
            int num = count;
            while ( num > 0 ) {
                try {
                    runnable.run();
                    return;
                } catch (Throwable e) {
                    num = num - 1;
                    e.printStackTrace();
                }
            }
        }

    }

}
